/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius.fedoraaccess.rest;

import cz.mzk.rehan.commons.Dom4jUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.XPath;

/**
 *
 * @author Martin Řehánek <rehan at mzk.cz>
 */
abstract class AbstractOperation {

    private static final Logger logger = Logger.getLogger(AbstractOperation.class.getName());
    protected final HttpConnector connector;

    protected AbstractOperation(HttpConnector connector) {
        this.connector = connector;
    }

    protected String getBaseUrl() {
        return connector.getBaseUrl();
    }

    protected List<String> extractPidList(Document resultDoc) {
        XPath xpath = Dom4jUtils.createXPath("/fedora:result/fedora:resultList/fedora:objectFields/fedora:pid/text()");
        List<Node> nodes = xpath.selectNodes(resultDoc);
        return toStringList(nodes);
    }

    private List<String> toStringList(List<Node> nodeList) {
        List<String> result = new ArrayList<String>(nodeList.size());
        for (Node node : nodeList) {
            result.add(node.getText());
        }
        return result;
    }

    protected String encodeAttribute(String attributeValue) {
        try {
            return URLEncoder.encode(attributeValue, "utf-8");
        } catch (UnsupportedEncodingException ex) {
            logger.log(Level.SEVERE, null, ex);
            return "";
        }
    }
}
